package controller;

import annotation.Controller;
import annotation.GetMapping;
import annotation.PostMapping;
import entity.UserEntity;
import result.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {
    @GetMapping("/")
    public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        if (session.getAttribute("user") != null) {
            Map<String, Object> result = new HashMap<>();
            Object attribute = session.getAttribute("user");
            result.put("user", attribute);
            return new ModelAndView(result, "user-profile.html");
        }
        // 未登录，跳转到登录页:
        return new ModelAndView("login.html");
    }

    @PostMapping("/login")
    public ModelAndView login(
            UserEntity userEntity,
            HttpServletRequest request,
            HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>();
        if (userEntity.getPassword().equals(userEntity.getName())) {
            HttpSession session = request.getSession();
            session.setAttribute("user", userEntity);
            result.put("user", userEntity);
            return new ModelAndView(result, "user-profile.html");
        }
        result.put("status", "fail");
        result.put("errorMsg", "账号或密码错误");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return new ModelAndView(result, "error-msg.html");
    }
}
